package com.android.kmlmrg.services.rest.method;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpStatus;
import org.json.JSONObject;

import android.app.Application;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;

import com.android.kmlmrg.R;
import com.android.kmlmrg.event.RestLoginEvent;
import com.android.kmlmrg.listener.custom.RestLoginListener;
import com.android.kmlmrg.listener.custom.UsersListener;
import com.android.kmlmrg.model.ApiSession;
import com.android.kmlmrg.services.ServiceController;
import com.google.gson.Gson;

public class Login extends AsyncTask<Void, Integer, String> {


	/**LOG**/
	private static final  String LOG_TAG = Login.class.getSimpleName();

	private static final String METHODE_NAME = "/login";

	private String login = null;

	private String password = null;

	private ApiSession vApiSession = null;
	
	private static ArrayList<RestLoginListener> listeners = new ArrayList<RestLoginListener>();

	private Application application;
	
	int code;
	
	private boolean isFromFormView;
	
	
	
	
	public Login(Application pApplication, String pLogin, String pPassword, boolean pIsFromFormView ) {	
		Log.i(LOG_TAG, "START - Constructeur Login ");
		application = pApplication;

		this.login = pLogin;
		this.password = pPassword;	
		
		isFromFormView = pIsFromFormView;

		Log.i(LOG_TAG, "END - Constructeur Login");
	}

	protected String doInBackground(Void... sUrl) {
		try {
			String vUrl = this.application.getString(R.string.user_endpoint) + METHODE_NAME ;
			vApiSession = new ApiSession(login,password,application.getString(R.string.wsCallerId),application.getString(R.string.wsCallerSecret));
		
			JSONObject vJsonObject = new JSONObject();
			vJsonObject.put(ApiSession.WSCALLERID, vApiSession.getWsCallerId() );
			vJsonObject.put(ApiSession.TIMESTAMP, vApiSession.getTimesTamp());
			vJsonObject.put(ApiSession.HASH,vApiSession.getHash());
			vJsonObject.put(ApiSession.IDENTIFIANT,vApiSession.getIdentifiant());
			vJsonObject.put(ApiSession.PASSWORD,vApiSession.getPassword());
			String message = vJsonObject.toString();

			URLConnection url = new URL(vUrl).openConnection();
			HttpURLConnection httpcon = (HttpURLConnection) ((new URL(vUrl).openConnection()));
			httpcon.setConnectTimeout(15 * 1000);
			httpcon.setRequestProperty("Content-Type", "application/json");
			httpcon.setRequestProperty("Accept", "application/json");
			httpcon.setRequestMethod("POST");

			httpcon.setDoInput(true);
			httpcon.setDoOutput(true);
			httpcon.setFixedLengthStreamingMode(message.getBytes().length);
			httpcon.connect();


			OutputStream os = new BufferedOutputStream(httpcon.getOutputStream());
			os.write(message.getBytes());
			//clean up
			os.flush();


			// this will be useful so that you can show a typical 0-100% progress bar
			int fileLength = httpcon.getContentLength();
			
			 code = httpcon.getResponseCode();

			// download the file

			InputStream input = httpcon.getInputStream();
			BufferedReader r = new BufferedReader(new InputStreamReader(input));
			StringBuilder total = new StringBuilder();
			String line;
			while ((line = r.readLine()) != null) {
				total.append(line);
			}
			os.flush();
			os.close();
			input.close();	

			return total.toString();
		} catch (SocketTimeoutException e) {
			code = 0;
			return "SocketTimeoutException";
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}



	@Override
	protected void onPostExecute(String result) {
		Log.i(LOG_TAG, "START - onPostExecute");		
		Log.i(LOG_TAG, "result : " + result);
		Log.i(LOG_TAG, "" + code);	
		RestLoginEvent vEvent = new  RestLoginEvent(this, false, null, isFromFormView);
		if (code == HttpStatus.SC_OK) {
			Gson vGson = new Gson();
			ApiSession vSession = vGson.fromJson(result, ApiSession.class);
			vApiSession.setSessionToken(vSession.getSessionToken());
			vApiSession.setStatus(vSession.getStatus());
			if ( vApiSession.getStatus().trim().equalsIgnoreCase("true") ) {			

				vEvent = new RestLoginEvent(this, true, vApiSession, isFromFormView);
			} else {
				vEvent = new RestLoginEvent(this, false, vApiSession, isFromFormView);
			}
			
		} 
		fireEvent(vEvent);
		if (isFromFormView){

		}
		Log.i(LOG_TAG, "END - onPostExecute");
	}


	@Override
	protected void onCancelled() {
		Log.i(LOG_TAG, "START - onCancelled ");
		Log.i(LOG_TAG, "END - onCancelled ");
	}

	@Override
	protected void onCancelled(String result) {
		Log.i(LOG_TAG, "START - onCancelled ");
		Log.i(LOG_TAG, "END - onCancelled ");
		super.onCancelled(result);
	}


	

	private void fireEvent( RestLoginEvent pEvent ){		
		for(RestLoginListener listener : listeners){
			listener.resultLoginRequest( pEvent );
		}
	}

	public static void addListener ( RestLoginListener pListener ){
		listeners.add(pListener);
	}
	
	public static void removeListener( UsersListener pListener ){
		listeners.remove(pListener);
	}



}
